/*
 *  Copyright (c) 2023-2025 苏州棱镜七彩信息科技有限公司 (Suzhou PrismAurora Information Technology Co.,Ltd)
 *  sbom-generate is licensed under Mulan PSL v2.
 *  You can use this software according to the terms and conditions of the Mulan PSL v2.
 *  You may obtain a copy of Mulan PSL v2 at:
 *           http://license.coscl.org.cn/MulanPSL2
 *  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *  See the Mulan PSL v2 for more details.
 * */
package com.ljqc.parameter.validator;

import com.beust.jcommander.IParameterValidator;
import com.beust.jcommander.ParameterException;

import java.util.regex.Pattern;

public class HostValidator implements IParameterValidator {
    private static final String URL_REGEX = "^" +
            // 协议部分（必填）
            "(?:https?|ftp)://" +
            // 用户名密码验证（可选）
            "(?:\\S+(?::\\S*)?@)?" +
            // 主机地址部分（支持域名/IPv4/IPv6）
            "(?:" +
            // 域名验证
            "(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,63}" +
            "|" +
            // IPv4地址验证
            "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" +
            "|" +
            // IPv6地址验证
            "(\\[([a-fA-F0-9:]+)])" +
            ")" +
            // 端口号验证（可选）
            "(?::\\d{1,5})?" +
            // 路径验证（可选）
            "(?:[/?#][^\\s\"<>]*?)?" +
            "$";
    // 编译正则模式（忽略大小写）
    private static final Pattern URL_PATTERN = Pattern.compile(URL_REGEX, Pattern.CASE_INSENSITIVE);

    public static boolean isValidUrl(String url) {
        return URL_PATTERN.matcher(url).matches();
    }

    @Override
    public void validate(String name, String value)
            throws ParameterException {
        try {
            if (!isValidUrl(value)) {
                throw new ParameterException("参数 【" + name + "】 格式校验失败，请输入有效的openapi地址：【" + value + "】，原因：openapi地址验证失败");
            }
        } catch (Exception e) {
            throw new ParameterException("参数 【" + name + "】 格式校验失败，请输入有效的openapi地址：【" + value + "】，原因：openapi地址验证失败");
        }
    }
}
